<?php
namespace app\services;
use app\services\CreativeService;

class TanxService extends BaseService {
	public 	$appKey = '21660096';
	public  $appSecret = '1007cc60a415bc019d93bb6cb483b797';
	public  $memberId = 110200045;
	public  $tokenBaseKey = 'd63b3a9cad6c4ffab6ac947ada881353';
	public  $pubUrl = 'http://gw.api.taobao.com/router/rest?';

	public function addTanxCreative($creativeId = '') {
		$tanx_support = \Yii::$app->params['tanx_support'];
		if (!$tanx_support) return;

		$serv = new CreativeService();
		//目前只进行banner创意同步，若要进行video将查询条件的s.form = 0去掉
		$sql = "select c.id, c.category_id, c.click_monitor_url, c.adomain_full, c.landing_page, c.width,
				c.height, c.form, s.creative_code from {{%creative}} as c inner join {{%creative_ssp}} as s 
				on c.id = s.creative_id and s.ad_network_id = 2 and s.form = 0 and s.status = 0";
		if ($creativeId) {
			$sql = $sql." and c.id = $creativeId";
		}
		$creatives = $this->queryAll($sql);
		foreach ($creatives as $creative) {
		//参数数组
			$creativeArr = $this->formAddCreativeArray($creative);
		//生成签名
			$sign = $this->createSign($creativeArr);
		//组织参数
			$strParam = $this->createStrParam($creativeArr);
			$strParam .= 'sign='.$sign;
		//访问服务
			$url = $this->pubUrl.$strParam; 
			$result = file_get_contents($url);
			$result = json_decode($result, true);
			$result = $result['tanx_creative_add_response'];
			if($result['is_ok']) {
				$serv->updateSspCreative($creative['id'], 2, 'upload'); 
			}
		}
	}

	public function formAddCreativeArray($creative) {
		$paramArr = [];
		$time = time();
		$paramArr['app_key'] = $this->appKey;
		$paramArr['method'] = 'taobao.tanx.creative.add';
		$paramArr['format'] = 'json';
		$paramArr['v'] = '2.0';
		$paramArr['sign_method'] = 'md5';
		$paramArr['timestamp'] = date('Y-m-d H:i:s');
		$paramArr['member_id'] = $this->memberId;
		$paramArr['token'] = md5($this->tokenBaseKey.$time);
		$paramArr['sign_time'] = $time;
		$paramArr['creative_id'] = $creative['id'];
		$paramArr['adboard_type'] = $this->mapCategoryId($creative['category_id']);
		$value = $creative['click_monitor_url'].$creative['landing_page'];
		$paramArr['adboard_data'] = str_replace('%%CLICK_URL%%', $value, $creative['creative_code']);
		$paramArr['destination_url'] = $creative['adomain_full'];
		$paramArr['adboard_size'] = "{$creative['width']}".'x'."{$creative['height']}";
		$creative['form'] == 0 && $paramArr['creative_package_format'] = 1;
		$creative['form'] == 1 && $paramArr['creative_package_format'] = 2;
		return $paramArr;
	}

	public function getTanxCreative($creativeId = '') {
		$tanx_support = \Yii::$app->params['tanx_support'];
		if (!$tanx_support) return;

		$serv = new CreativeService();
		$where = "ad_network_id = 2 and ssp_audit_status = 0";
		if ($creativeId) {
			$where = "creative_id = $creative and ad_network_id = 2 ";
		} else {
			$time = date('Y-m-d 00:00:00', strtotime('-2 day'));
			$where .= " and last_update>='$time'";
		}
        $sspCreatives = $this->getAll('CreativeSsp', $where);
        foreach ($sspCreatives as $sspCreative) {
        	$creativeArr = $this->formGetCreativeArray($sspCreative['creative_id']);
			$sign = $this->createSign($creativeArr);
			$strParam = $this->createStrParam($creativeArr);
			$strParam .= 'sign='.$sign;
			$url = $this->pubUrl.$strParam; 
			$result = file_get_contents($url);
			$result = json_decode($result,true);
			$auditStatus['status'] = $sspCreative['status'];
			$result = $result['tanx_creative_get_response'];
			if($result['is_ok']) {
				$result['result']['status'] == 'PASS' && $auditStatus['ssp_audit_status'] = 2;
				$result['result']['status'] == 'REFUSE' && $auditStatus['ssp_audit_status'] = 3;
				$result['result']['status'] == 'WAITING' && $auditStatus['ssp_audit_status'] = 0;
				$serv->updateSspCreative($result['result']['creative_id'], 2, 'status', $auditStatus); 
			}
        }
	} 

	public function getTanxCreativeInfo($creativeId) {
		$tanx_support = \Yii::$app->params['tanx_support'];
		if (!$tanx_support) return;

		$serv = new CreativeService();
		$where = "creative_id = $creativeId and ad_network_id = 2 ";
		$sspCreative = $this->getOne('CreativeSsp', $where);
		if (!$sspCreative) return false;
		$creativeArr = $this->formGetCreativeArray($sspCreative['creative_id']);
		$sign = $this->createSign($creativeArr);
		$strParam = $this->createStrParam($creativeArr);
		$strParam .= 'sign='.$sign;
		$url = $this->pubUrl.$strParam; 
		$result = file_get_contents($url);
		$result = json_decode($result,true);
		return $result;
	} 


	public function formGetCreativeArray($creativeId) {
		$paramArr = [];
		$time = time();
		$paramArr['app_key'] = $this->appKey;
		$paramArr['method'] = 'taobao.tanx.creative.get';
		$paramArr['format'] = 'json';
		$paramArr['v'] = '2.0';
		$paramArr['sign_method'] = 'md5';
		$paramArr['timestamp'] = date('Y-m-d H:i:s');
		$paramArr['member_id'] = $this->memberId;
		$paramArr['token'] = md5($this->tokenBaseKey.$time);
		$paramArr['sign_time'] = $time;
		$paramArr['creative_id'] = $creativeId;
		return $paramArr;
	}

	public function getAllTanxCreatives() {
		$tanx_support = \Yii::$app->params['tanx_support'];
		if (!$tanx_support) return;

		$serv = new CreativeService();
        $sql = "select creative_id, status from {{%creative_ssp}} where status=1 and ad_network_id=2";
        $sspCreatives = $this->queryAll($sql);
        $sspCreatives = $this->arrayGroup($sspCreatives, 'creative_id');

		$creativeArr = $this->formGetAllCreativesArray();
		$sign = $this->createSign($creativeArr);
		$strParam = $this->createStrParam($creativeArr);
		$strParam .= 'sign='.$sign;
		$url = $this->pubUrl.$strParam; 
		$result = file_get_contents($url);
		$result = json_decode($result, true);
		$result = $result['tanx_creatives_get_response'];
		if($result['is_ok']) {
			$datas = $result['results']['creative_dto'];
			foreach ($datas as $data) {
				if(!isset($sspCreatives[$data['creative_id']])) continue;
				$auditStatus['status'] = $sspCreatives[$data['creative_id']][0]['status']; 
				$data['status'] == 'PASS' && $auditStatus['ssp_audit_status'] = 2;
				$data['status'] == 'REFUSE' && $auditStatus['ssp_audit_status'] = 3;
				$data['status'] == 'WAITING' && $auditStatus['ssp_audit_status'] = 0;
				$serv->updateSspCreative($data['creative_id'], 2, 'status', $auditStatus); 
			}
		}
	}

	public function formGetAllCreativesArray() {
		$paramArr = [];
		$time = time();
		$paramArr['app_key'] = $this->appKey;
		$paramArr['method'] = 'taobao.tanx.creatives.get';
		$paramArr['format'] = 'json';
		$paramArr['v'] = '2.0';
		$paramArr['sign_method'] = 'md5';
		$paramArr['timestamp'] = date('Y-m-d H:i:s');
		$paramArr['member_id'] = $this->memberId;
		$paramArr['token'] = md5($this->tokenBaseKey.$time);
		$paramArr['sign_time'] = $time;
		$paramArr['status'] = 'ALL';   //创意的状态ALL,通过PASS，拒绝REFUSE，未审核WAITING
		$paramArr['page'] = 1;   //分页的页码（第一页为1）
		return $paramArr;
	}

	//签名函数
	public function createSign ($paramArr) {
     	$sign = $this->appSecret;
     	ksort($paramArr);
     	foreach ($paramArr as $key => $val) {
         	if ($key != '' && $val != '') {
             	$sign .= $key.$val;
         }
     	}
    	$sign.=$this->appSecret;
     	$sign = strtoupper(md5($sign));
     	return $sign;
	}

	//组参函数
	public function createStrParam ($paramArr) {
     	$strParam = '';
     	foreach ($paramArr as $key => $val) {
     		if ($key != '' && $val != '') {
            	$strParam .= $key.'='.urlencode($val).'&';
         	}
     	}
     	return $strParam;
	}

	public function mapCategoryId($categoryId) {
		$sql = "select vam_category_id, category_id from {{%creative_category_map}} where ad_network_id = 2 and vam_category_id = $categoryId";
		$result = $this->queryOne($sql);
		return $result['category_id'];
	}
}